package wxy;

import java.util.ArrayList;
import java.util.List;
import java.util.Stack;

public class LeetCode1106 {
    public boolean parseBoolExpr(String expression) {
        Stack<Character> stack = new Stack<>();
        for (int i = 0; i < expression.length(); i++) {
            char c = expression.charAt(i);
            if (c == ',') {
                continue;
            } else if (c == ')') {
                List<Character> operandList = new ArrayList<>();
                while (stack.peek() != '(') {
                    operandList.add(stack.pop());
                }
                stack.pop();
                char op = stack.pop();
                if (op == '!') {
                    stack.push(operandList.get(0) == 't' ? 'f' : 't');
                } else if (op == '|') {
                    stack.push(operandList.contains('t') ? 't' : 'f');
                } else {
                    stack.push(operandList.contains('f') ? 'f' : 't');
                }
            } else {
                stack.push(c);
            }
        }
        return stack.pop() == 't';
    }
}
